package com.matou.auth.service;

import com.matou.auth.manager.UserManager;
import com.matou.server.api.system.po.TUser;
import com.matou.server.api.system.res.CmAuthUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @Author CM
 * @Date 2021/5/8 16:47
 * @Description CmUserDetailService
 * @Version 1.0
 */
@Component
public class CmUserDetailService implements UserDetailsService {

    @Autowired
    private UserManager userManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser systemUser = userManager.findByName(username);
        if (systemUser != null) {
            String permissions = userManager.findUserPermissions(systemUser.getId());
            boolean notLocked = false;
            if (TUser.STATUS_VALID.equals(systemUser.getRemove())){
                notLocked = true;
            }
            String encode = passwordEncoder.encode("123456");
            System.out.println(encode);
            CmAuthUser authUser = new CmAuthUser(systemUser.getEmail(), systemUser.getPassword(), true, true, true, notLocked,
                    AuthorityUtils.commaSeparatedStringToAuthorityList(permissions));
            BeanUtils.copyProperties(systemUser,authUser);
            return authUser;
        } else {
            throw new UsernameNotFoundException("账号或密码错误");
        }
    }

}
